package com.ji.zhiqu.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ji.zhiqu.model.dto.question.QuestionContentDTO;
import com.ji.zhiqu.model.entity.App;
import com.ji.zhiqu.model.entity.Question;
import com.ji.zhiqu.model.entity.ScoringResult;
import com.ji.zhiqu.model.entity.UserAnswer;
import com.ji.zhiqu.model.vo.QuestionVO;
import com.ji.zhiqu.service.QuestionService;
import com.ji.zhiqu.service.ScoringResultService;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 打分类app自定义测评策略
 */
@ScoringStrategyConfig(appType = 0, scoringStrategy = 0)  // @ScoringStrategyConfig 中包含了 @Component
public class CustomScoreScoringStrategy implements ScoringStrategy {
    @Resource
    private QuestionService questionService;
    @Resource
    ScoringResultService scoringResultService;

    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        // 1. 根据appId查询题目和题目结果信息（按分数降序排序）
        Long appId = app.getId();
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, appId)
        );

        List<ScoringResult> scoringResultList = scoringResultService.list(
                Wrappers.lambdaQuery(ScoringResult.class)
                        .eq(ScoringResult::getAppId, appId)
                        .orderByDesc(ScoringResult::getResultScoreRange)  // 按分数降序排序
        );

        // 2. 统计用户总得分
        int totalScore = 0;
        // 题目列表
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDTO> questionContent = questionVO.getQuestionContent();

        // questionContentDTO 含 List<Option> options
        // Option 含 String result; int score; String value; String key;

        // TODO：测试这个逻辑
        // 遍历题目列表
        int i = 0;
        for (QuestionContentDTO questionContentDTO : questionContent) {
            // 得到答案列表 ["A","B","A","D"...] 对应的答案
            if(i >= choices.size()) break;
            String answer = choices.get(i++);
            // 遍历题目中的选项
            for (QuestionContentDTO.Option option : questionContentDTO.getOptions()) {
                // 如果答案和选项的key匹配
                if (option.getKey().equals(answer)) {
                    // 获取选项的score属性，若没填则为0
                    // Integer score = Optional.ofNullable(option.getScore()).orElse(0);
                    int score = Optional.of(option.getScore()).orElse(0);
                    totalScore += score;
                }
            }
        }

        // 3. 遍历每种得分结果，得到第一个用户的得分大于得分范围的结果
        ScoringResult maxScoringResult = scoringResultList.get(0);
        for (ScoringResult scoringResult : scoringResultList) {
           if(totalScore >= scoringResult.getResultScoreRange()) {
               maxScoringResult = scoringResult;
               break;
           }
        }

        // 4. 构造返回值，填充答案对象的属性
        UserAnswer userAnswer = new UserAnswer();
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        userAnswer.setResultId(maxScoringResult.getId());
        userAnswer.setResultName(maxScoringResult.getResultName());
        userAnswer.setResultDesc(maxScoringResult.getResultDesc());
        userAnswer.setResultPicture(maxScoringResult.getResultPicture());
        userAnswer.setResultScore(totalScore);
        return userAnswer;
    }
}
